<?php

/**
 * @Author: Mr.Mao
 * @Date:   2021-05-31 09:46:50
 * @Last Modified by:   Mr.Mao
 * @Last Modified time: 2021-06-02 17:44:32
 */
/**
 * 腾讯云存储
 */
require('cos-php-sdk-v5/index.php');
use app\mainadmin\model\StorageModel;
class storage
{
	public $obj;
	public $config;
	public $bucket;
	// 初始化
	public function __construct(){
		$where = [];
		$where[] = ['type','=','cos'];
		$info = (new StorageModel)->getInfo($where);
		$this->config = $info['config'];
		$this->obj = new Qcloud\Cos\Client(
		    array(
		        'region' => $this->config['region'],
		        'credentials'=> array(
		            'secretId'  => $this->config['secretId'],
		            'secretKey' => $this->config['secretKey']
		        )
		    )
		);
		$this->bucket = $this->config['bucket'];
	}
	/**
	 * [createBucket 创建存储桶]
	 * @param  string $bucket [存储桶名称]
	 */
	public function createBucket($bucket='')
	{
		try {
		    $result = $this->obj->createBucket(array('Bucket' => $bucket));
		    //请求成功
		} catch (\Exception $e) {
			$data['code'] = 0;
			$data['msg'] = $e->getMessage();
		    //请求失败
		    return $data;
		}
		$data['code'] = 1;
	    return $data;
	}

	// $res = $storage->createBucket('my-test-mao');

	/**
	 * [getListBuckets  获取存储桶列表]
	 */
	public function getBucketList()
	{
		try {
		    //请求成功
		    $result = $this->obj->listBuckets();
		} catch (\Exception $e) {
		    $data['code'] = 0;
			$data['msg'] = $e->getMessage();
		    //请求失败
		    return $data;
		}
		$data['code'] = 1;
		$list = [];
	    foreach($result['Buckets'] as $v) {
	    	foreach ($v['Bucket'] as $bucket) {
	    		$list[] = $bucket;
	    	}
		    
		}
		$data['list'] = $list;
	    return $data;
	}
	/**
	 * [deleteBucket 删除桶]
	 * @param  string $bucket [桶名称]
	 */
	public function deleteBucket($bucket='')
	{
		try {
		    $result = $this->obj->deleteBucket(array(
		        'Bucket' => $bucket //格式：BucketName-APPID
		    )); 
		    // 请求成功
		} catch (\Exception $e) {
		    $data['code'] = 0;
			$data['msg'] = $e->getMessage();
		    //请求失败
		    return $data;
		}
		$data['code'] = 1;
	    return $data;
	}

	/**
	 * [getListObjects 获取对象列表]
	 * @param  array  $param [请求参数]
	 * @param  $param['Bucket'] String 必须 [存储桶名称，格式：BucketName-APPID]
	 * @param  $param['Delimiter'] String 可选 [默认为空，设置分隔符，例如设置/来模拟文件夹]
	 * @param  $param['EncodingType'] String 可选 [默认不编码，规定返回值的编码方式，可选值：url]
	 * @param  $param['Marker'] String 可选 [默认以 UTF-8 二进制顺序列出条目，标记返回 objects 的 list 的起点位置]
	 * @param  $param['Prefix'] String 可选 [默认为空，对 object 的 key 进行筛选，匹配指定前缀（prefix）的 objects]
	 * @param  $param['MaxKeys'] Int 可选 [最多返回的 objects 数量，默认为最大的1000]
	 */
	public function listObjects($param = [])
	{	
		$res = $this->obj->listObjects(['Bucket'=>$this->bucket]);
		print_r($res);
	}

	/**
	 * [upload 上传文件]
	 * @param  string $object [文件名]
	 * @param  array  $file   [上传的文件]
	 */
	public function upload($object = '',$file = [])
	{

		try { 
		  	$result = $this->obj->putObject(array( 
		      	'Bucket' => $this->bucket, //格式：BucketName-APPID 
		      	'Key' => $object, 
		      	'Body' => fopen($file['tmp_name'], 'rb'),
		      	'ContentType' => $file['type'],
		  	)); 
		  	// 请求成功 
		} catch (\Exception $e) { 
		  	$data['code'] = 0;
			$data['msg'] = $e->getMessage();
		    //请求失败
		    return $data;
		}
		$data['code'] = 1;
		$data['url'] = $result['Location'];
	    return $data;
	}

	/**
	 * [copyObject 复制对象]
	 * @param  string $object [对象名称]
	 */
	public function copyObject($from_object , $to_object )
	{
		try {
		  	$result = $this->obj->copyObject(array(
		      	'Bucket' => $this->bucket, //格式：BucketName-APPID
		      	'Key' => $from_object,
		      	'CopySource' => $this->config['domain'].'/'.$to_object,
		 	)); 
		  	// 请求成功
		} catch (\Exception $e) {
		  	$data['code'] = 0;
			$data['msg'] = $e->getMessage();
		    return $data;
		}
		return ['code' => 1];
	}

	/**
	 * [deleteObject 删除单个文件]
	 * @param  string $object [文件名称]
	 */
	public function deleteObject($object='')
    {
        try{
		    $result = $this->obj->deleteObject(array(
		      	'Bucket' => $this->bucket, //格式：BucketName-APPID
		      	'Key' => $object
		  	));
		} catch(OssException $e) {
		    $data['code'] = 0;
			$data['msg'] = $e->getMessage();
		    return $data;
		}
		return ['code' => 1];
    }

    /**
     * [deleteObjects 删除多个文件]
     * @param  array  $objects [删除对象]
     */
	public function deleteObjects($objects=[])
    {
    	$delObjs = [];
    	foreach ($objects as $object) {
    		$delObjs[]['Key'] = $object;
    	}
        try{
		    $this->obj->deleteObjects(array(
		      	'Bucket' => $this->bucket, //格式：BucketName-APPID
		      	'Objects' => $delObjs
		  	));
		} catch(OssException $e) {
		    $data['code'] = 0;
			$data['msg'] = $e->getMessage();
		    return $data;
		}
		return ['code' => 1];
    }
}